package com.neu.controller;


import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.github.pagehelper.PageInfo;
import com.neu.common.AutoLog;
import com.neu.common.CaptureConfig;
import com.neu.common.Result;
import com.neu.entity.Admin;
import com.neu.entity.Book;
import com.neu.entity.Params;
import com.neu.service.AdminService;
import com.neu.utils.SMSUtils;
import com.wf.captcha.utils.CaptchaUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@CrossOrigin
@RestController
@RequestMapping("/admin")
public class AdminController {

    @Autowired
    private AdminService adminService;

    @Autowired
    private JavaMailSender sender;

    @GetMapping
    public Result findAll(){
        List<Admin> list = adminService.getAll();

        return Result.success(list);

    }

    @GetMapping("/search")
    public Result findBySearch(Params params) {
        PageInfo<Admin> info = adminService.findBySearch(params);
        return Result.success(info);
    }

    @GetMapping("/searchTutor")
    public Result findBySearchTutor(Params params) {
        PageInfo<Admin> info = adminService.findBySearchTutor(params);
        return Result.success(info);
    }

    @PostMapping
    public Result add(@RequestBody Admin admin){
        if(admin.getId() == null){
            adminService.add(admin);
        }else{
            adminService.update(admin);
        }

        return Result.success();
    }

    @PutMapping
    public Result update(@RequestBody Admin admin){
        adminService.updateTutor(admin);
        return Result.success();
    }

    @PutMapping("/betutor")
    public Result betutor(@RequestBody Admin admin){
        adminService.updateTutor(admin);
        return Result.success();
    }

    @PutMapping("/evaluate")
    public Result evaluate(@RequestBody Admin admin){
        adminService.evaluateTutor(admin);
        return Result.success();
    }

    @DeleteMapping("/{id}")
    public Result delete(@PathVariable Integer id){
        adminService.delete(id);
        return Result.success();
    }

    @PostMapping("/login")
    @AutoLog("登录该系统")
    public Result login(@RequestBody Admin admin, @RequestParam String key, HttpServletRequest request){
        //判断验证码对不对
        if(!admin.getVerCode().toLowerCase().equals(CaptureConfig.CAPTURE_MAP.get(key))){
            //如果不相等，说明验证不通过
            CaptchaUtil.clear(request);

            return  Result.error("验证码不正确");
        }
        Admin loginUser = adminService.login(admin);
        CaptureConfig.CAPTURE_MAP.remove(key);
        return Result.success(loginUser);
    }
    @PostMapping("/register")
    public Result register(@RequestBody Admin admin){
        adminService.add(admin);

        return Result.success();
    }

    @PutMapping("/reset")
    public Result resetPassword(@RequestBody Admin admin){
        adminService.updatePassword(admin);

        return Result.success();
    }

    @GetMapping("/echarts/bie")
    public Result bie(){
        //查询出所有图书
        List<Admin> list= adminService.findAll();
        Map<String,Long> collect = list.stream()
                .filter(x -> ObjectUtil.isNotEmpty(x.getTypeName()))
                .collect(Collectors.groupingBy(Admin::getTypeName,Collectors.counting()));
        //最后返回给前端的数据结构
        List<Map<String,Object>> mapList = new ArrayList<>();
        if(CollectionUtil.isNotEmpty(collect)){
            for(String key: collect.keySet()){
                Map<String,Object> map = new HashMap<>();
                map.put("name",key);
                map.put("value",collect.get(key));
                mapList.add(map);
            }
        }
        return Result.success(mapList);
    }


    @GetMapping("/echarts/bar")
    public Result bar(){
        //查询出所有图书
        List<Admin> list= adminService.findAll();
        Map<String,Long> collect = list.stream()
                .filter(x -> ObjectUtil.isNotEmpty(x.getTypeName()))
                .collect(Collectors.groupingBy(Admin::getTypeName,Collectors.counting()));
        List<String> xAxis = new ArrayList<>();
        List<Long> yAxis = new ArrayList<>();
        if(CollectionUtil.isNotEmpty(collect)){
            for(String key: collect.keySet()){
                xAxis.add(key);
                yAxis.add(collect.get(key));
            }
        }

        Map<String,Object> map = new HashMap<>();
        map.put("xAxis",xAxis);
        map.put("yAxis",yAxis);

        return Result.success(map);
    }

    @GetMapping("/sendMsg")
    public Result sendMsg(HttpServletRequest request){
        //获取手机号
        String phone = "15694278522";
//        String message = request.getParameter("message").toString();
        String message = request.getParameter("message");
        if (message == null) {
            return Result.error("消息内容不能为空");
        }
        System.out.println("message : " + message);
        if(StringUtils.hasText(phone)){

            //调用阿里云提供的短信服务API完成发送短信
            SMSUtils.sendMessage("阿里云短信测试","SMS_154950909",phone,message);


            return Result.success();
        }

        return Result.error("短信发送失败");
    }

    @GetMapping("/sendEmail")
    public Result sendEmail(HttpServletRequest request){
        //获取手机号
        String subject = request.getParameter("subject");
        String setText = request.getParameter("setText");
        String setTo = request.getParameter("setTo");
        String setFrom = request.getParameter("setFrom");

        SimpleMailMessage mail = new SimpleMailMessage();
        mail.setSubject(subject);
        mail.setText(setText);
        mail.setTo(setTo);
        mail.setFrom(setFrom);
        sender.send(mail);
        System.out.println("邮箱发送完毕！");

        return Result.success();

    }



}
